package com.lms.nio.groupchat;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-05-09 06:57
 * @Description: ${Description}
 */
public class GroupChatServer {
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private static final Integer PORT = 6666;

    public GroupChatServer() {
        try {
            //得到选择器
            selector = Selector.open();
            //打开通道
            serverSocketChannel = ServerSocketChannel.open();
            //绑定端口
            serverSocketChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞
            serverSocketChannel.configureBlocking(false);
            //注册到选择器
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listen() {
        try {
            while (true) {
                //最多等待2秒，获取有事件的key
                int count = selector.select(2000);
                if (count > 0) {
                    //获取key集合
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    //循环得到有事件的key
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        //如果有连接事件，监听连接
                        if (key.isAcceptable()) {
                            //获取客户端通道
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            //设置非阻塞
                            socketChannel.configureBlocking(false);
                            //注册到选择器，绑定读事件（可以说绑定多个） socketChannel.register(selector,SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                            socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                            System.out.println(socketChannel.getRemoteAddress() + "上线");
                        }
                        //如果有读取事件，处理逻辑
                        if (key.isReadable()) {
                            readMsg(key);

                        }
                        //将key从兴趣集中删除
                        iterator.remove();
                    }
                } else {
//                    System.out.println("等待连接...");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Author 李孟帅
     * @Description 读取客户端消息
     * @Date 7:14 2020/5/9
     **/
    public void readMsg(SelectionKey key) {

        //获取客户端通道
        SocketChannel channel = (SocketChannel) key.channel();
        //创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {

            //读取到缓冲区
            int read = channel.read(buffer);
            //判断是否读完
            if (read > 0) {
                buffer.flip();
                String msg = new String(buffer.array(), buffer.position(), buffer.limit());
                buffer.clear();
                System.out.println("from 客户端:" + channel.getRemoteAddress() + " --->    " + msg);
                //向其他客户端转发消息
                sendMsgToOtherClients(msg, channel);
            } else {

            }

        } catch (IOException e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线了...");
                key.channel();
                channel.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }

    private void sendMsgToOtherClients(String msg, SocketChannel self) {
        System.out.println("服务器转发消息中...");
        //遍历所有注册到选择器中的通道，并排除自己
        for (SelectionKey key : selector.keys()) {
            //获取通道
            SelectableChannel targetChannel = key.channel();
            //遍历不包含自己的客户端通道
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                SocketChannel dest = (SocketChannel) targetChannel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                try {
                    dest.write(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static void main(String[] args) {
        GroupChatServer server = new GroupChatServer();
        server.listen();
    }
}
